import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Button, 
  Space, 
  Typography, 
  Card,
  Row,
  Col,
  message,
  Slider,
  Switch,
  Select,
  Tooltip
} from 'antd';
import {
  ThunderboltOutlined,
  SaveOutlined,
  StarOutlined,
  BulbOutlined,
  RocketOutlined
} from '@ant-design/icons';

import GraphVisualizationHub from '../../../../components/GraphVisualizationHub';

const { Text, Title } = Typography;
const { Option } = Select;

// 布局定义
const LAYOUT_DEFINITIONS = {
  // 经典布局
  force: {
    name: '力导向布局',
    description: '基于物理模拟的节点自然分布',
    icon: <ThunderboltOutlined />,
    category: 'classic',
    parameters: {
      nodeStrength: { name: '节点斥力系数', min: 0.1, max: 2.0, default: 0.8, step: 0.1 },
      linkStrength: { name: '关系引力系数', min: 0.1, max: 2.0, default: 0.6, step: 0.1 },
      centerForce: { name: '中心引力', min: 0, max: 1, default: 0.1, step: 0.05 }
    }
  },
  circular: {
    name: '环形布局',
    description: '节点均匀分布在圆周上',
    icon: <div style={{ width: 14, height: 14, border: '2px solid currentColor', borderRadius: '50%' }} />,
    category: 'classic',
    parameters: {
      radius: { name: '圆环半径', min: 100, max: 500, default: 250, step: 10 },
      startAngle: { name: '起始角度', min: 0, max: 360, default: 0, step: 15 },
      clockwise: { name: '顺时针排列', type: 'boolean', default: true }
    }
  },
  tree: {
    name: '树状布局',
    description: '层级分明的树形结构',
    icon: <div style={{ fontSize: '14px' }}>🌳</div>,
    category: 'classic',
    parameters: {
      direction: { name: '展开方向', type: 'select', options: ['TB', 'BT', 'LR', 'RL'], default: 'TB' },
      nodeSpacing: { name: '节点间距', min: 50, max: 300, default: 120, step: 10 },
      levelSpacing: { name: '层级间距', min: 80, max: 400, default: 150, step: 10 }
    }
  },
  radial: {
    name: '辐射布局',
    description: '从中心向外辐射的结构',
    icon: <div style={{ fontSize: '14px' }}>☀️</div>,
    category: 'classic',
    parameters: {
      centerRadius: { name: '中心半径', min: 50, max: 200, default: 100, step: 10 },
      radiusStep: { name: '半径递增', min: 50, max: 200, default: 80, step: 10 }
    }
  },
  
  // 创意布局
  petal: {
    name: '花瓣形布局',
    description: '如花瓣般优雅的节点排列',
    icon: <div style={{ fontSize: '14px' }}>🌸</div>,
    category: 'creative',
    parameters: {
      petalCount: { name: '花瓣数量', min: 3, max: 12, default: 6, step: 1 },
      petalRadius: { name: '花瓣半径', min: 100, max: 400, default: 200, step: 10 }
    }
  },
  spiral: {
    name: '螺旋形布局',
    description: '螺旋式的动态美感',
    icon: <div style={{ fontSize: '14px' }}>🌀</div>,
    category: 'creative',
    parameters: {
      spiralTightness: { name: '螺旋紧密度', min: 0.1, max: 2.0, default: 0.8, step: 0.1 },
      spiralTurns: { name: '螺旋圈数', min: 1, max: 10, default: 3, step: 0.5 }
    }
  },
  honeycomb: {
    name: '蜂窝形布局',
    description: '六边形蜂窝状排列',
    icon: <div style={{ fontSize: '14px' }}>🍯</div>,
    category: 'creative',
    parameters: {
      hexSize: { name: '六边形大小', min: 30, max: 100, default: 60, step: 5 },
      spacing: { name: '蜂窝间距', min: 5, max: 30, default: 10, step: 2 }
    }
  }
};

// 布局分类
const LAYOUT_CATEGORIES = {
  classic: {
    name: '经典布局',
    icon: <StarOutlined />
  },
  creative: {
    name: '创意布局',
    icon: <BulbOutlined />
  }
};

/**
 * 图谱样式选择器组件
 */
const GraphStyleSelector = ({
  visible, 
  onCancel, 
  initialData = { nodes: [], edges: [] },
  initialLayout = 'force',
  onApplyLayout
}) => {
  // 核心状态
  const [currentLayout, setCurrentLayout] = useState(initialLayout);
  const [layoutParameters, setLayoutParameters] = useState({});
  const [graphNodes, setGraphNodes] = useState([]);
  const [graphEdges, setGraphEdges] = useState([]);

  // 初始化数据
  useEffect(() => {
    if (initialData && initialData.nodes && initialData.nodes.length > 0) {
      setGraphNodes(JSON.parse(JSON.stringify(initialData.nodes || [])));
      setGraphEdges(JSON.parse(JSON.stringify(initialData.edges || [])));
    }
  }, [initialData]);

  // 初始化布局参数
  useEffect(() => {
    const layoutDef = LAYOUT_DEFINITIONS[currentLayout];
    if (layoutDef && layoutDef.parameters) {
      const defaultParams = {};
      Object.entries(layoutDef.parameters).forEach(([key, param]) => {
        defaultParams[key] = param.default;
      });
      setLayoutParameters(defaultParams);
    }
  }, [currentLayout]);

  // 应用布局
  const handleApplyLayout = () => {
    if (onApplyLayout) {
      onApplyLayout({
        layout: currentLayout,
        parameters: layoutParameters,
        nodes: graphNodes,
        edges: graphEdges
      });
      onCancel();
      message.success(`已应用${LAYOUT_DEFINITIONS[currentLayout]?.name}布局`);
    }
  };

  // 按分类获取布局
  const getLayoutsByCategory = (category) => {
    return Object.entries(LAYOUT_DEFINITIONS)
      .filter(([_, layout]) => layout.category === category)
      .map(([key, layout]) => ({ key, ...layout }));
  };

  // 渲染布局选择器
  const renderLayoutSelector = () => (
    <div>
      {Object.entries(LAYOUT_CATEGORIES).map(([categoryKey, category]) => {
        const layouts = getLayoutsByCategory(categoryKey);
        return (
          <div key={categoryKey} style={{ marginBottom: 16 }}>
            <div style={{ marginBottom: 8 }}>
              <Space>
                {category.icon}
                <Text strong>{category.name}</Text>
              </Space>
            </div>
            <Row gutter={[8, 8]}>
              {layouts.map(layout => (
                <Col key={layout.key} span={6}>
                  <Tooltip title={layout.description}>
                    <Button
                      type={currentLayout === layout.key ? 'primary' : 'default'}
                      size="middle"
                      block
                      onClick={() => setCurrentLayout(layout.key)}
                      style={{ 
                        height: 'auto', 
                        padding: '8px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <Space>
                        {layout.icon}
                        <span>{layout.name}</span>
                      </Space>
                    </Button>
                  </Tooltip>
                </Col>
              ))}
            </Row>
          </div>
        );
      })}
    </div>
  );

  // 渲染参数调试面板
  const renderParameterPanel = () => {
    const layoutDef = LAYOUT_DEFINITIONS[currentLayout];
    if (!layoutDef || !layoutDef.parameters) return null;

    return (
      <Card 
        size="small" 
        title={`${layoutDef.name}参数调整`}
        style={{ marginTop: 16 }}
      >
        <Row gutter={[16, 12]}>
          {Object.entries(layoutDef.parameters).map(([paramKey, param]) => (
            <Col key={paramKey} span={12}>
              <div style={{ marginBottom: 8 }}>
                <Text strong style={{ fontSize: '12px' }}>
                  {param.name}
                </Text>
              </div>
              {param.type === 'boolean' ? (
                <Switch
                  checked={layoutParameters[paramKey]}
                  onChange={(checked) => 
                    setLayoutParameters(prev => ({ ...prev, [paramKey]: checked }))
                  }
                />
              ) : param.type === 'select' ? (
                <Select
                  value={layoutParameters[paramKey]}
                  onChange={(value) => 
                    setLayoutParameters(prev => ({ ...prev, [paramKey]: value }))
                  }
                  size="small"
                  style={{ width: '100%' }}
                >
                  {param.options.map(option => (
                    <Option key={option} value={option}>{option}</Option>
                  ))}
                </Select>
              ) : (
                <Slider
                  min={param.min}
                  max={param.max}
                  step={param.step}
                  value={layoutParameters[paramKey]}
                  onChange={(value) => 
                    setLayoutParameters(prev => ({ ...prev, [paramKey]: value }))
                  }
                  tooltip={{ formatter: (value) => `${value}` }}
                />
              )}
            </Col>
          ))}
        </Row>
      </Card>
    );
  };

  return (
    <Modal
      title="图谱样式选择"
      open={visible}
      onCancel={onCancel}
      width={1000}
      centered={true}
      styles={{ body: { padding: '16px' } }}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button 
          key="save" 
          type="primary" 
          icon={<SaveOutlined />} 
          onClick={handleApplyLayout}
        >
          应用布局
        </Button>
      ]}
    >
      <Row gutter={16}>
        {/* 左侧控制面板 */}
        <Col span={8}>
          <Title level={5} style={{ marginBottom: 12 }}>选择布局样式</Title>
          {renderLayoutSelector()}
          {renderParameterPanel()}
        </Col>
        
        {/* 右侧可视化区域 */}
        <Col span={16}>
          <div style={{ 
            border: '1px solid #d9d9d9', 
            borderRadius: '6px',
            background: '#fff',
            height: 500,
            position: 'relative'
          }}>
            {/* 可视化组件 */}
            <GraphVisualizationHub
              nodes={graphNodes}
              edges={graphEdges}
              layout={currentLayout}
              layoutParameters={layoutParameters}
              onLayoutChange={setCurrentLayout}
              editable={false}
              height={500}
              errorHandler={(error) => {
                console.error("布局渲染错误:", error);
                message.error('布局渲染出现问题');
              }}
            />
            
            {/* 布局信息显示 */}
            <div style={{ 
              position: 'absolute', 
              bottom: 12, 
              left: 12,
              zIndex: 10
            }}>
              <Card size="small" style={{ minWidth: 200 }}>
                <Space direction="vertical" size="small">
                  <div>
                    <Text strong>{LAYOUT_DEFINITIONS[currentLayout]?.name}</Text>
                    <Text type="secondary" style={{ marginLeft: 8, fontSize: '11px' }}>
                      {LAYOUT_DEFINITIONS[currentLayout]?.category === 'classic' ? '经典' : '创意'}
                    </Text>
                  </div>
                  <div>
                    <Text style={{ fontSize: '12px' }}>
                      节点: {graphNodes.length} | 关系: {graphEdges.length}
                    </Text>
                  </div>
                </Space>
              </Card>
            </div>
          </div>
        </Col>
      </Row>
    </Modal>
  );
};

export default GraphStyleSelector;